package cn.qxq1.springevent.event;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
//@EnableAsync 这里可以  但是不能实现applicationListener接口
public class MyEventListener {
    private Logger log = LoggerFactory.getLogger(MyEventListener.class);

//    @Override
    public void onApplicationEvent(MyEvent<User> userMyEvent) {
        //todo  非注解方式不生效  原因？？
        User user = (User) userMyEvent.getSource();
        log.info("----start-----");
        log.info("----send email to [ " + user.getEmail() + " ]-----");
        log.info("-----end-----");
    }

    /**
     *  注解 同步 监听
     */
    @EventListener
    public void annoListen(MyEvent<User> event) {
        User user = (User) event.getSource();
        log.info("----anno start-----");
        log.info("anno send email to [ " + user.getEmail() + " ]");
        log.info("-----anno end-----");
    }

    /**
     * 注解 异步 监听
     */
    @EventListener
    @Async
    public void annoAsyncListen(MyEvent<User> event) {
        User user = (User) event.getSource();
        log.info("----anno async start-----");
        log.info("anno async send email to [ " + user.getEmail() + " ]");
        log.info("-----anno async end-----");
    }


    /**
     * 注解 异步 监听
     */
    @EventListener
    @Async(value = "logExecutor")//可以指定异步线程池的名字
    public void annoAsyncListen2(MyEvent<User> event) {
        User user = (User) event.getSource();
        log.info("----anno async2 start-----");
        log.info("anno async2 send email to [ " + user.getEmail() + " ]");
        log.info("-----anno async2 end-----");
    }
}

